package com.yfbao.horizon.inspection.prometheus;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class PrometheusHttpClient {

    private final OkHttpClient httpClient;
    private final String prometheusBaseUrl;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public PrometheusHttpClient(@Value("${prometheus.url:http://localhost:9090}") String prometheusBaseUrl) {
        this.prometheusBaseUrl = prometheusBaseUrl;
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
                .build();
    }

    /**
     * 执行PromQL查询
     */
    public PrometheusResponse executeQuery(String promQL) throws IOException {
        String encodedQuery = URLEncoder.encode(promQL, StandardCharsets.UTF_8.toString());
        String url = String.format("%s/api/v1/query?query=%s", prometheusBaseUrl, encodedQuery);

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json")
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (response.body() == null) {
                throw new RuntimeException("Prometheus响应体为空");
            }

            String responseBody = response.body().string();

            if (response.isSuccessful()) {
                return parseResponse(responseBody);
            } else {
                throw new RuntimeException("Prometheus查询失败: " + response.code());
            }
        }
    }

    /**
     * 执行范围查询
     */
    public PrometheusResponse executeRangeQuery(String promQL, long start, long end, String step) throws IOException {
        String encodedQuery = URLEncoder.encode(promQL, StandardCharsets.UTF_8.toString());
        String url = String.format("%s/api/v1/query_range?query=%s&start=%d&end=%d&step=%s",
                prometheusBaseUrl, encodedQuery, start, end, step);

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/json")
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (response.body() == null) {
                throw new RuntimeException("Prometheus响应体为空");
            }

            String responseBody = response.body().string();
            return parseResponse(responseBody);
        }
    }

    private PrometheusResponse parseResponse(String responseBody) throws IOException {
        return objectMapper.readValue(responseBody, PrometheusResponse.class);
    }
}
